package com.jun.common.core.utils;

/**
 * @author yuejun.li
 * @date 2024/8/1 11:10:24
 */

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.jun.common.core.model.AuthHeader;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;

/**
 * 提供身份认证
 */
@Slf4j
public class IdentifyAuthUtils {

    /**
     * 密钥在正反10分钟内有效
     *
     * @param header
     * @param salt
     * @return
     */
    public static boolean auth(AuthHeader header, String salt){
        if(Objects.nonNull(header)){
            LocalDateTime now = LocalDateTime.now();
            long afterNow = now.plusMinutes(10).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            long beforeNow = now.plusMinutes(-10).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Long signTime;
            try {
                signTime = Long.valueOf(header.getSign());
                if(signTime > beforeNow && signTime < afterNow){
                    MD5 md5 = SecureUtil.md5();
                    md5.setSalt(salt.getBytes());
                    String str = md5.digestHex(header.getSign());
                    log.info("MD5加密后的盐：{}",str);
                    System.out.println("MD5加密后的盐：" + str);
                    if(Objects.equals(header.getSignEnc(), str)){
                        return true;
                    }
                }
            } catch (NumberFormatException e) {
                return false;
            }
        }

        return false;
    }


}
